package com.ddd.mill.infrastructure.event;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class EventBusConfig {
    @Value("${event-bus.thread-pool.core-pool-size}")
    private int corePoolSize;

    @Value("${event-bus.thread-pool.max-pool-size}")
    private int maximumPoolSize;

    @Value("${event-bus.thread-pool.keep-alive-time}")
    private int keepAliveTime;

    @Value("${event-bus.thread-pool.allow-core-thread-timeOut}")
    private boolean allowCoreThreadTimeOut;

    //定义事件总线bean
    @Bean
    public EventBus eventBus() {
        // 使用JDK提供的线程池类构建配置
        ThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(corePoolSize);
        threadPoolExecutor.setMaximumPoolSize(maximumPoolSize);
        threadPoolExecutor.setKeepAliveTime(keepAliveTime, TimeUnit.SECONDS);
        threadPoolExecutor.allowCoreThreadTimeOut(allowCoreThreadTimeOut);
        AsyncEventBus eventBus = new AsyncEventBus("asyncEventBus", threadPoolExecutor);
        return eventBus;
    }
}
